package org.com.Controller;


import Entity.User;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import org.com.Service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 277
 * @since 2025-09-14
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public User login(@RequestBody User user, HttpServletRequest request) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, user.getPhone()).eq(User::getPassword, user.getPassword());
        User one = userService.getOne(wrapper);
        if (one == null) {
            return null;
        }
        request.getSession().setAttribute("user", one.getId());
        request.getSession().setMaxInactiveInterval(60 * 60 * 24 * 7);
        stringRedisTemplate.opsForValue().set("login:user:", String.valueOf(one.getId()));
        stringRedisTemplate.expire("login:user:", 50, TimeUnit.MINUTES);
        return one;
    }

    @PostMapping("/regist")
    public User register(@RequestBody User user) {
        user.setPhone(user.getPhone());
        user.setPassword(user.getPassword());
        user.setEmail(user.getEmail());
        user.setName("user" + user.getName() + (UUID.randomUUID().toString().substring(0, 5)));
        user.setNickname(UUID.randomUUID().toString() + (user.getName().substring(5)));
        user.setCreateTime(LocalDateTime.now());
        return userService.save(user) ? user : null;
    }
    @GetMapping("/list")
    public List<User> list() {
        return userService.list();
    }
}
